# -*- coding: utf-8 -*-

import serial
import threading
import Queue

class Miniterm(object):
    def __init__(self, port, baudrate, RxQ, TxQ):
        self.serial = serial.Serial(port, baudrate, timeout = 1)
        self.RxQ = RxQ
        self.TxQ = TxQ

    def _start_reader(self):
        """Start reader thread"""
        self._reader_alive = True
        # start serial->console thread
        self.receiver_thread = threading.Thread(target=self.reader)
        self.receiver_thread.setDaemon(True)
        self.receiver_thread.start()

    def _stop_reader(self):
        """Stop reader thread only, wait for clean exit of thread"""
        self._reader_alive = False
        self.receiver_thread.join()


    def start(self):
        self.alive = True
        self._start_reader()
        # enter console->serial loop
        self.transmitter_thread = threading.Thread(target=self.writer)
        self.transmitter_thread.setDaemon(True)
        self.transmitter_thread.start()

    def stop(self):
        self.alive = False

    def join(self, transmit_only=False):
        self.transmitter_thread.join()
        if not transmit_only:
            self.receiver_thread.join()
        self.serial.close()

    def reader(self):
        try:
            while self.alive and self._reader_alive:
                data = self.serial.read(1)
                if data != '':
                    self.RxQ.put(data)
            print 'Thread Reader Exit'
        except:
            print 'Thread Reader'
            raise

    def writer(self):
        try:
            print 'write'
            while self.alive:
                if not self.TxQ.empty():
                    data = self.TxQ.get()
                    self.serial.write(data)
            print 'Thread Writer Exit'
        except:
            print 'Thread writer'
            raise
 